package SwingDrawImage;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

//绘制图片类，需要提供一个图片路径来构建该类的对象

public class PictureView extends JPanel {
    private int width;
    private int height;
    private Color bgColor;
    private BufferedImage img;


    public PictureView(String imagePath) throws IOException {
        System.out.println("加载图片......");
        File file = new File(imagePath);
        img = ImageIO.read(file);
    }

    public void setImg(String imgPath) throws IOException {
        System.out.println("加载图片......");
        File file = new File(imgPath);
        img = ImageIO.read(file);
    }

    public void setBgColor(Color bgColor){
        this.bgColor = bgColor;
        this.repaint();
    }

    public void draw(Graphics g){
        System.out.println("正在绘图");
        width = this.getWidth();
        height = this.getHeight();
        int imgW = img.getWidth();
        int imgH = img.getHeight();
//        float period = (float) height / width;

        int drawWidth = width;
        int drawHeight =(int) (width * ((float) imgH / imgW));

        if(drawHeight > height){
            drawHeight = height;
            drawWidth = (int) (height * ((float) imgW / imgH));
        }
        g.drawImage(img, ((width - drawWidth) / 2), ((height - drawHeight) / 2), drawWidth, drawHeight, null);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(bgColor != null){
            g.setColor(this.bgColor);
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
        }

        this.draw(g);
    }
}
